import re
import os
import requests

# 创建保存图片的文件夹
if not os.path.exists('downloaded_csdn_images'):
    os.makedirs('downloaded_csdn_images')
url = "https://blog.csdn.net/2303_77470379?spm=1010.2135.3001.5343"
headers = {
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36"

}
response = requests.get(url,headers=headers)
response.raise_for_status()  # 检查请求是否成功
html = response.text
# print(html)

result = re.findall(r"<img src=(.*?)>",html)
# print(result)
# image_urls = []
#
# for img in result:
#     match = re.search(r'"([^"]+)"', img)
#     if match:
#         img_url = match.group(1)
#         if img_url.startswith('//'):
#             img_url = 'https:' + img_url
#         elif not img_url.startswith('http'):
#             img_url = 'https://blog.csdn.net' + img_url
#         image_urls.append(img_url)
#         print(f"发现图片URL: {img_url}")
# # 下载并保存图片
# for i, img_url in enumerate(image_urls):
#     try:
#         # 下载图片
#         img_response = requests.get(img_url, headers=headers, timeout=10)
#         img_response.raise_for_status()
#
#         # 提取文件名或使用序号命名
#         if '.' in img_url.split('/')[-1]:
#             filename = img_url.split('/')[-1]
#         else:
#             filename = f'image_{i}.jpg'
#
#         # 保存图片
#         with open(f'../downloaded_csdn_images/{filename}', 'wb') as f:
#             f.write(img_response.content)
#
#         print(f"已保存: {filename}")
#
#     except Exception as e:
#         print(f"下载 {img_url} 失败: {str(e)}")




